﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;


namespace 学院学生管理系统
{
    class VerifyCodeImgSimple
    {
        /// <summary>
        /// 生成随机字符码
        /// </summary>
        /// <param name="length">字符串长度</param>
        /// <returns></returns>
        public string CreateVerifyCode(int length)
        {
            string code = "";
            string baseChar = "0123456789abcdefghijklmnopqrstuvwxyz";
            Random rnd = new Random();
            for (int i = 1; i <= length; i++)
            {
                code += baseChar[rnd.Next(baseChar.Length)].ToString();
            }
            return code;
        }
        /// <summary>
        /// 生成校验码图片
        /// </summary>
        /// <param name="code">验证码字符</param>
        /// <param name="fontSize">字号</param>
        /// <param name="font">字体</param>
        /// <param name="foreColor">前景色</param>
        /// <param name="bgColor">背景色</param>
        /// <returns></returns>
        public Bitmap CreateImage(string code, int fontSize, string font, Color foreColor, Color bgColor)
        {
            int imageWidth = (code.Length * fontSize) + 40;
            int imageHeight = fontSize * 2 + 10;
            Bitmap image = new Bitmap(imageWidth, imageHeight);
            Graphics g = Graphics.FromImage(image);
            g.Clear(bgColor);
            Font fnt = new Font(font, fontSize, FontStyle.Bold);
            g.DrawString(code, fnt, new SolidBrush(foreColor), 1, 1);
            Random rnd = new Random();
            for (int i = 1; i <= 1000; i++)
            {
                int x = rnd.Next(imageWidth);
                int y = rnd.Next(imageHeight);
                g.FillRectangle(new SolidBrush(Color.FromArgb(rnd.Next())), x, y, 2, 2);
            }
            for (int i = 1; i <= 50; i++)
            {
                int x1 = rnd.Next(imageWidth);
                int y1 = rnd.Next(imageHeight);
                int x2 = rnd.Next(imageWidth);
                int y2 = rnd.Next(imageHeight);
                g.DrawLine(new Pen(Color.FromArgb(rnd.Next()), 2), x1, y1, x2, y2);
            }
            return image;
        }
    }
}
